import axios, { type AxiosResponse, type AxiosRequestHeaders } from 'axios';
import { showNotify} from 'vant';
import {getToken} from './token'

interface ResponseData<T> {
	ret?: number;
	data: T;
	message: string;
	code?:number
	ok?:string
}

// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: `/denglu`,
	timeout: 50000,
});

// 添加请求拦截器
service.interceptors.request.use(
	(config) => {

		let token = getToken()
		if (token) {
			(config.headers as AxiosRequestHeaders).token = token
		}

		return config;
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	async (response: AxiosResponse<ResponseData<any>>) => {
		let res = response.data 
		if(res.code === 200) {
			return res.data
		}else {
			return Promise.reject(res)
		}
		
	},
	(error) => {
		// 对响应错误做点什么
		if (error.message.indexOf('timeout') != -1) {
			showNotify({ type: 'warning', message: '网络超时' });

		} else if (error.message == 'Network Error') {
			showNotify({ type: 'warning', message: '网络连接错误' });
		
		} else {
			if (error.response.data) showNotify({ type: 'warning', message: 'error.response.statusText' });
			else showNotify({ type: 'warning', message: '接口路径找不到' });
		
		}
		return Promise.reject(error);
	}
);

export default service;
